package com.wxd.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.wxd.reggie.common.BaseContext;
import com.wxd.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取当前访问路径的URI -- 即除了ip和端口之外的部分
        String requestURI = request.getRequestURI();
        // 1. 设定访问的白名单
        String[] whiteUrl = new String[]{
                "/employee/login",
                "/employee/logout",
                "/common/upload",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        // 2. 判断当前的请求是否在白名单中 若在则放行 封装要判断的方法
        Boolean flag = checkWhite(whiteUrl, requestURI);
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }
        // 3. 若不在白名单中 则判断当前是否是登录状态 是-则放行 否-返回未登录结果 R.error(msg)
        if (request.getSession().getAttribute("employee") != null) {
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        //4-2、判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 检查当前路径是否在白名单中
     *
     * @param whiteUrls
     * @param URI
     */
    public Boolean checkWhite(String[] whiteUrls, String URI) {
        for (String uri : whiteUrls) {
            boolean match = PATH_MATCHER.match(uri, URI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
